package com.situ.stmall.manger.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.stmall.manger.entity.Goods;
import com.situ.stmall.manger.entity.GoodsPic;
import com.situ.stmall.manger.mapper.GoodsMapper;
import com.situ.stmall.manger.service.GoodsPicService;
import com.situ.stmall.manger.service.GoodsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsPicService goodsPicService;

    @Override
    @Transactional(//开事务
            isolation = Isolation.SERIALIZABLE, //隔离级别
            propagation = Propagation.REQUIRED,  //事务的传播机制  七个记住
            rollbackFor = Exception.class //回滚,当方法中抛出异常时回滚事务
    )
    public int add(Goods goods) throws Exception {
        //只会添加goods，不会添加图片
        //保存商品的数据，和商品图片的数据
        //先保存商品
        int code = goodsMapper.insert(goods);
        if (code > 0) {
            //再保存图片
            for (GoodsPic pic : goods.getPics()) {
                pic.setGoodsId(goods.getId());
            }
            goodsPicService.addPatch(goods.getPics());
        }

        //图片数据在goods里面
        return code;
    }

    @Override
    public int remove(Integer id) throws Exception {
        Goods goods = goodsMapper.selectById(id);
        if (goods == null) {
            throw new Exception("ID不存在");
        }
        //只会删除goods，不会删除图片
        return goodsMapper.delete(id);
    }

    @Override
    public int edit(Goods goods) throws Exception {
        Goods sgoods = goodsMapper.selectById(goods.getId());
        if (sgoods == null) {
            throw new Exception("ID不存在");
        }
        //只会修改goods，不会修改图片
        return goodsMapper.update(goods);
    }

    @Override
    public Goods getById(Integer id) throws Exception {
        Goods goods = goodsMapper.selectById(id);
        if (goods == null) {
            throw new Exception("ID不存在");
        }
        return goods;
    }

    @Override
    public List<Goods> search(Goods goods) {

        return goodsMapper.select(goods);
    }

    @Override
    public PageInfo searchByPage(Integer page, Integer limit, Goods goods) {
        PageHelper.startPage(page, limit);
        List<Goods> list = goodsMapper.select(goods);
        return new PageInfo(list);
    }
}
